<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>IndexedDB + Vue 任务管理</title>

    <!-- 引入 Vue 2.7 -->
    <script src="./libs/vue.min.js"></script>

    <!-- 引入 Element UI 样式 -->
    <link rel="stylesheet" href="./libs/element-ui.css" />

    <!-- 引入 Element UI -->
    <script src="./libs/element-ui.js"></script>
  </head>
  <body>
    <div id="app">
      <el-container>
        <el-header>
          <h1>{{ title }}</h1>
        </el-header>

        <el-main>
          <el-button type="primary" @click="initDB">初始化数据库</el-button>
          <el-button type="danger" @click="closeDB">关闭数据库连接</el-button>

          <el-input v-model="taskInput" placeholder="输入任务名称" style="margin: 10px 0"></el-input>
          <el-button type="success" @click="addTask">添加任务</el-button>
          <el-button type="info" @click="loadTasks">加载任务列表</el-button>
          <el-button type="warning" @click="exportDatabase">导出数据库</el-button>
          <el-button type="primary" @click="importDatabase">导入数据库</el-button>
          <el-button type="danger" @click="clearDatabase">清空数据库</el-button>
          <el-button type="danger" @click="deleteDatabase">删除数据库</el-button>

          <el-table :data="tasks" style="width: 100%; margin-top: 20px" border>
            <el-table-column prop="name" label="任务名称" width="300"></el-table-column>
            <el-table-column prop="created" label="创建时间"></el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button type="danger" size="mini" @click="deleteTask(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>

        <el-footer>
          <p style="text-align: center">IndexedDB 任务管理系统</p>
        </el-footer>
      </el-container>
    </div>

    <script>
      new Vue({
        el: '#app',
        data: {
          title: 'IndexedDB + Vue 任务管理',
          dbName: 'TaskDatabase', // 数据库名称
          storeName: 'Tasks', // 对象存储名称
          db: null, // 数据库实例
          taskInput: '', // 输入框绑定值
          tasks: [] // 任务列表
        },
        methods: {
          checkDatabaseInitialized() {
            if (!this.db) {
              this.$message.error('数据库未初始化，请先点击“初始化数据库”按钮')
              return false
            }
            return true
          },
          // 初始化数据库
          initDB() {
            const request = indexedDB.open(this.dbName, 1)

            request.onupgradeneeded = (event) => {
              this.db = event.target.result
              if (!this.db.objectStoreNames.contains(this.storeName)) {
                this.db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true })
              }
              this.$message.success('数据库初始化成功')
            }

            request.onsuccess = (event) => {
              this.db = event.target.result
              this.$message.success('数据库连接成功')
            }

            request.onerror = (event) => {
              this.$message.error('数据库连接失败')
              console.error('数据库连接失败', event)
            }
          },
          // 关闭数据库连接
          closeDB() {
            if (!this.checkDatabaseInitialized()) return // 检查数据库是否初始化

            this.db.close() // 关闭数据库连接
            this.db = null // 清空数据库实例
            this.$message.success('数据库连接已关闭')
          },
          // 添加任务
          addTask() {
            if (!this.checkDatabaseInitialized()) return // 检查数据库是否初始化

            if (!this.taskInput.trim()) {
              this.$message.warning('请输入任务名称')
              return
            }

            const transaction = this.db.transaction(this.storeName, 'readwrite')
            const store = transaction.objectStore(this.storeName)
            const task = { name: this.taskInput, created: new Date().toISOString() }

            const request = store.add(task)

            request.onsuccess = () => {
              this.$message.success('任务添加成功')
              this.taskInput = ''
              this.loadTasks()
            }

            request.onerror = (event) => {
              this.$message.error('任务添加失败')
              console.error('任务添加失败', event)
            }
          },
          // 加载任务
          loadTasks() {
            if (!this.checkDatabaseInitialized()) return // 检查数据库是否初始化
            const transaction = this.db.transaction(this.storeName, 'readonly')
            const store = transaction.objectStore(this.storeName)
            const request = store.getAll()

            request.onsuccess = (event) => {
              this.tasks = event.target.result
            }

            request.onerror = (event) => {
              this.$message.error('加载任务失败')
              console.error('加载任务失败', event)
            }
          },

          // 删除任务
          deleteTask(taskId) {
            if (!this.checkDatabaseInitialized()) return // 检查数据库是否初始化

            const transaction = this.db.transaction(this.storeName, 'readwrite')
            const store = transaction.objectStore(this.storeName)
            const request = store.delete(taskId)

            request.onsuccess = () => {
              this.$message.success('任务删除成功')
              this.loadTasks()
            }

            request.onerror = (event) => {
              this.$message.error('任务删除失败')
              console.error('任务删除失败', event)
            }
          },
          // 清空数据库
          clearDatabase() {
            if (!this.checkDatabaseInitialized()) return // 检查数据库是否初始化

            const transaction = this.db.transaction(this.storeName, 'readwrite')
            const store = transaction.objectStore(this.storeName)
            const request = store.clear()

            request.onsuccess = () => {
              this.$message.success('数据库已清空')
              this.tasks = []
            }

            request.onerror = (event) => {
              this.$message.error('清空数据库失败')
              console.error('清空数据库失败', event)
            }
          },
          // 导出数据库
          exportDatabase() {
            if (!this.checkDatabaseInitialized()) return // 检查数据库是否初始化
            const transaction = this.db.transaction(this.storeName, 'readonly')
            const store = transaction.objectStore(this.storeName)
            const request = store.getAll()

            request.onsuccess = (event) => {
              const data = event.target.result
              const blob = new Blob([JSON.stringify(data)], { type: 'application/json' })
              const url = URL.createObjectURL(blob)
              const a = document.createElement('a')
              a.href = url
              a.download = `${this.dbName}.json`
              a.click()
              URL.revokeObjectURL(url)
              this.$message.success('数据库导出成功')
            }

            request.onerror = (event) => {
              this.$message.error('数据库导出失败')
              console.error('数据库导出失败', event)
            }
          },

          // 导入数据库
          importDatabase() {
            // 如果数据库未初始化，尝试重新初始化
            if (!this.db) {
              this.$message.info('检测到数据库未初始化，正在重新初始化...')
              const request = indexedDB.open(this.dbName, 1)

              request.onupgradeneeded = (event) => {
                this.db = event.target.result
                if (!this.db.objectStoreNames.contains(this.storeName)) {
                  this.db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true })
                }
                this.$message.success('数据库重新初始化成功')
              }

              request.onsuccess = (event) => {
                this.db = event.target.result
                this.$message.success('数据库连接成功')
                this.importDatabase() // 重新调用导入方法
              }

              request.onerror = (event) => {
                this.$message.error('数据库初始化失败，无法导入文件')
                console.error('数据库初始化失败', event)
              }

              return
            }

            const input = document.createElement('input')
            input.type = 'file'
            input.accept = 'application/json'

            input.onchange = (event) => {
              const file = event.target.files[0]
              if (file) {
                const reader = new FileReader()
                reader.onload = (e) => {
                  try {
                    const data = JSON.parse(e.target.result)

                    const transaction = this.db.transaction(this.storeName, 'readwrite')
                    const store = transaction.objectStore(this.storeName)

                    data.forEach((item) => {
                      store.put(item)
                    })

                    transaction.oncomplete = () => {
                      this.$message.success('数据库导入成功')
                      this.loadTasks()
                    }

                    transaction.onerror = (event) => {
                      this.$message.error('数据库导入失败')
                      console.error('数据库导入失败', event)
                    }
                  } catch (error) {
                    this.$message.error('文件解析失败，请确保导入的是正确的 JSON 文件')
                    console.error('文件解析失败', error)
                  }
                }
                reader.readAsText(file)
              }
            }

            input.click()
          },

          // 删除数据库
          deleteDatabase() {
            const request = indexedDB.deleteDatabase(this.dbName)

            request.onsuccess = () => {
              this.$message.success('数据库已删除')
              this.db = null // 清空数据库实例
              this.tasks = [] // 清空任务列表
            }

            request.onerror = (event) => {
              this.$message.error('删除数据库失败')
              console.error('删除数据库失败', event)
            }

            request.onblocked = () => {
              this.$message.warning('删除数据库被阻止，请关闭其他页面的连接')
            }
          }
        }
      })
    </script>
  </body>
</html>
